package com.cskaoyan.demo7.service;

import com.cskaoyan.demo7.bean.model.MarketCart;
import com.cskaoyan.demo7.bean.model.MarketCartExample;
import com.cskaoyan.demo7.bean.model.MarketGoods;
import com.cskaoyan.demo7.bean.model.MarketGoodsProduct;
import com.cskaoyan.demo7.bean.req.CartCheckedVo;
import com.cskaoyan.demo7.bean.resp.CartIndexVo;
import com.cskaoyan.demo7.mapper.MarketCartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description：
 * @Author：BLUEBLANK
 * @Date：2024/4/23 19:43
 */

@Service("cartService")
public class CartServiceImpl implements CartService {
    @Autowired
    private MarketCartMapper marketCartMapper;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsProductService goodsProductService;


    @Override
    public CartIndexVo index(Integer userId) {
        CartIndexVo cartIndexVo = new CartIndexVo();
        // 查询购物车信息
        List<MarketCart> marketCartList = selectCartListByUserId(userId);
        cartIndexVo.setCartList(marketCartList);
        // 创建CartTotalDTO对象
        CartIndexVo.CartTotalDTO cartTotalDTO = new CartIndexVo.CartTotalDTO();
        // 包装类，创建对象时，默认值都是null
        cartTotalDTO.setCheckedGoodsAmount(BigDecimal.valueOf(0));
        cartTotalDTO.setCheckedGoodsCount(0);
        // 查询购物车中勾选的商品的总价和总件数
        marketCartList.stream().filter(MarketCart::getChecked).forEach(cart -> {
            cartTotalDTO.setCheckedGoodsAmount(cartTotalDTO.getCheckedGoodsAmount()
                    .add(cart.getPrice().multiply(new BigDecimal(cart.getNumber()))));
            cartTotalDTO.setCheckedGoodsCount(cartTotalDTO.getCheckedGoodsCount() + cart.getNumber());
        });


        // 查询购物车中商品的总价和总件数
        cartTotalDTO.setGoodsAmount(BigDecimal.valueOf(0));
        cartTotalDTO.setGoodsCount(0);
        marketCartList.stream().forEach(cart -> {
            cartTotalDTO.setGoodsAmount(cartTotalDTO.getGoodsAmount().add(cart.getPrice().multiply(new BigDecimal(cart.getNumber()))));
            cartTotalDTO.setGoodsCount(cartTotalDTO.getGoodsCount() + cart.getNumber());
        });

        cartIndexVo.setCartTotal(cartTotalDTO);

        return cartIndexVo;
    }


    @Override
    public CartIndexVo checked(Integer userId, CartCheckedVo cartCheckedVo) {
        // 直接转布尔型，会报错，因为map中存放的是Integer类型
        // Boolean isChecked = (Boolean) map.get("isChecked");
        // Integer isCheckedInt = (Integer) cartCheckedVo.get("isChecked");
        // // 转布尔型
        // Boolean isChecked = isCheckedInt == 1? true : false;

        // 不能转换为list<Integer>
        // List<Integer> productIds = (List<Integer>) map.get("productIds");
        List<Integer> productIds = cartCheckedVo.getProductIds();
        Integer isCheckedInt = cartCheckedVo.getIsChecked();
        // 转布尔型
        Boolean isChecked = isCheckedInt == 1;

        Date current = new Date();
        // 修改购物车中商品的勾选状态
        for (Integer productId : productIds) {
            MarketCart marketCart = new MarketCart();
            // 要更新的字段
            marketCart.setChecked(isChecked);
            marketCart.setUpdateTime(current);
            // 更新的条件
            MarketCartExample marketCartExample = new MarketCartExample();
            marketCartExample.createCriteria().andUserIdEqualTo(userId).andProductIdEqualTo(productId).andDeletedEqualTo(false);
            marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
        }

        // 查询购物车信息
        return index(userId);
    }

    @Override
    public Object add(Integer userId, Map map) {
        // {"goodsId":1181062,"number":4,"productId":319}
        Integer goodsId = (Integer) map.get("goodsId");
        Integer number = (Integer) map.get("number");
        Integer productId = (Integer) map.get("productId");
        // 判断商品是否存在
        // 上架状态，非删除状态
        MarketGoods marketGoods = goodsService.selectByPrimaryKey(goodsId);
        if (marketGoods == null) {
            return "商品不存在";
        }
        // 判断商品库存是否充足
        MarketGoodsProduct goodsProduct = goodsProductService.selectByPrimaryKey(productId);
        if (goodsProduct == null) {
            return "商品不存在";
        }

        if (goodsProduct.getNumber() < number) {
            return "库存不足";
        }
        // 判断商品是否已经在购物车中
        MarketCart marketCart = selectByUserIdAndProductIdAndGoodsId(userId, productId, goodsId);
        Date current = new Date();
        if (marketCart != null) {
            // 商品已经在购物车中，数量增加
            int endNum = marketCart.getNumber() + number;
            marketCart.setNumber(((short) endNum));
            marketCart.setUpdateTime(current);
            marketCartMapper.updateByPrimaryKeySelective(marketCart);
        } else {
            // 商品不在购物车中，添加到购物车
            MarketCart cart = new MarketCart();
            cart.setUserId(userId);
            cart.setProductId(productId);
            cart.setGoodsId(goodsId);
            cart.setNumber(number.shortValue());
            cart.setPrice(goodsProduct.getPrice());
            cart.setGoodsSn(marketGoods.getGoodsSn());
            cart.setGoodsName(marketGoods.getName());
            cart.setSpecifications(goodsProduct.getSpecifications());
            cart.setPicUrl(marketGoods.getPicUrl());
            cart.setAddTime(current);
            cart.setUpdateTime(current);
            marketCartMapper.insertSelective(cart);
        }
        // 返回购物车的商品总数
        return index(userId).getCartTotal().getGoodsCount();
    }

    @Override
    public Object fastadd(Integer userId, Map map) {
        Integer goodsId = (Integer) map.get("goodsId");
        Integer number = (Integer) map.get("number");
        Integer productId = (Integer) map.get("productId");
        // 判断商品是否存在
        // 上架状态，非删除状态
        MarketGoods marketGoods = goodsService.selectByPrimaryKey(goodsId);
        if (marketGoods == null) {
            return "商品不存在";
        }
        // 判断商品库存是否充足
        MarketGoodsProduct goodsProduct = goodsProductService.selectByPrimaryKey(productId);
        if (goodsProduct == null) {
            return "商品不存在";
        }
        if (goodsProduct.getNumber() < number) {
            return "库存不足";
        }

        // 判断商品是否已经在购物车中
        MarketCart marketCart = selectByUserIdAndProductIdAndGoodsId(userId, productId, goodsId);
        Date current = new Date();
        if (marketCart != null) {
            // 商品已经在购物车中，覆盖掉
            marketCart.setUpdateTime(current);
            marketCart.setNumber(number.shortValue());
            marketCartMapper.updateByPrimaryKey(marketCart);
            return marketCart.getId();
        } else {
            // 商品不在购物车中，添加到购物车
            MarketCart cart = new MarketCart();
            cart.setUserId(userId);
            cart.setProductId(productId);
            cart.setGoodsId(goodsId);
            cart.setNumber(number.shortValue());
            cart.setPrice(goodsProduct.getPrice());
            cart.setGoodsSn(marketGoods.getGoodsSn());
            cart.setGoodsName(marketGoods.getName());
            cart.setSpecifications(goodsProduct.getSpecifications());
            cart.setPicUrl(marketGoods.getPicUrl());
            cart.setAddTime(current);
            cart.setUpdateTime(current);
            marketCartMapper.insertSelective(cart);
            return cart.getId();
        }
    }

    private MarketCart selectByUserIdAndProductIdAndGoodsId(Integer userId, Integer productId, Integer goodsId) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria()
                .andDeletedEqualTo(false)
                .andUserIdEqualTo(userId)
                .andProductIdEqualTo(productId)
                .andGoodsIdEqualTo(goodsId);
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(cartExample);
        return marketCartList.size() > 0? marketCartList.get(0) : null;
    }


    private List<MarketCart> selectCartListByUserId(Integer userId) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria()
                .andDeletedEqualTo(false)
                .andUserIdEqualTo(userId);
        cartExample.setOrderByClause("add_time desc");
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(cartExample);
        return marketCartList;
    }
}
